﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KZ400B.AxleSettings;
namespace KZ400B.Controls
{
    public delegate void UnitChanged(string axleName, int newUnit);
    /// <summary>
    /// AxleSettings.xaml 的交互逻辑
    /// </summary>
    public partial class AxleSettings : UserControl
    {
        public event UnitChanged OnUnitChanged;
        string m_axleName = string.Empty;
        public AxleSettings()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(AxleSettings_Loaded);
        }
        //private Axle m_axle;
        void AxleSettings_Loaded(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(AxleName))
            {
                throw new Exception("AxleName 不能为空");
            }
            m_axleName = AxleName;
            labAxleName.Content = string.Format("{0}轴", AxleName);
            bind();
            //m_axle = AxleCacheManager.getAxle(AxleName);
            //if (m_axle != null)
            //{
            //    load();
            //}
            load();
        }

        public void Refresh()
        {
            //bind();

            //bindRunningUnits();
            //bindLeadDistances();
            //bindDriveRatios();
            //bindAxleDetailSettings();
            //bindRadians();
            load();
        }

        public void Save()
        {

            //commit to database
            int intValue = 0;
            double dValue = 0.0F;
            if (cmbPssType.SelectedValue != null && int.TryParse(cmbPssType.SelectedValue.ToString(), out intValue))
            {
                AxleCacheManager.AxleList[AxleName].PowerShiftStation = (PowerShiftStations)intValue;
            }

            if (cmbRunUnit.SelectedValue != null &&
                int.TryParse(cmbRunUnit.SelectedValue.ToString(), out intValue))
            {
                AxleCacheManager.AxleList[AxleName].RunningUnit = (RunningUnits)intValue;
            }

            dValue = 0.0F;
            if (cmbLeadDistance.SelectedItem != null &&
                double.TryParse(cmbLeadDistance.SelectedItem.ToString(), out dValue))
            {
                AxleCacheManager.AxleList[AxleName].LeadDistance = dValue;
            }
            dValue = 0.0F;
            if (cmbDriveRatio.SelectedItem != null &&
                double.TryParse(cmbDriveRatio.SelectedItem.ToString(), out dValue))
            {
                AxleCacheManager.AxleList[AxleName].DriveRatio = dValue;
            }
            if (cmbAxleDetailSetting.SelectedValue != null &&
                int.TryParse(cmbAxleDetailSetting.SelectedValue.ToString(), out intValue))
            {
                AxleCacheManager.AxleList[AxleName].AxleDetailSetting = intValue;
            }
            dValue = 0.0F;
            if (cmbRadian.SelectedValue != null &&
                double.TryParse(cmbRadian.SelectedValue.ToString(), out dValue))
            {
                AxleCacheManager.AxleList[AxleName].Radian = dValue;
            }
            labOnestepDisplacement.Content = getOnestepDisplacementString(AxleCacheManager.AxleList[AxleName].OnestepDisplacement);
            try
            {
                AxleCacheManager.Update(AxleCacheManager.AxleList[AxleName]);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void Reload()
        {
            load();
        }
        private void load()
        {
            try
            {
                if (AxleCacheManager.AxleList[AxleName] == null)
                {
                    return;
                }
                cmbPssType.SelectedValue = (int)AxleCacheManager.AxleList[AxleName].PowerShiftStation;

                bindRunningUnits();
                bindLeadDistances();
                bindDriveRatios();
                bindAxleDetailSettings();
                bindRadians();


                cmbRunUnit.SelectedValue = (int)AxleCacheManager.AxleList[AxleName].RunningUnit;
                //if (AxleCacheManager.AxleList[AxleName].LeadDistance != 0)
                //{
                    cmbLeadDistance.BindValue(AxleCacheManager.AxleList[AxleName].LeadDistance);
                //}
                //else
                //{
                //    cmbAxleDetailSetting.SelectedIndex = 0;
                //}
                //if (m_axle.DriveRatio != 0)
                //{
                cmbDriveRatio.BindValue(AxleCacheManager.AxleList[AxleName].DriveRatio);
                //}
                //else
                //{
                //    cmbDriveRatio.SelectedIndex = 0;
                //}
                cmbAxleDetailSetting.SelectedValue = AxleCacheManager.AxleList[AxleName].AxleDetailSetting;
                cmbRadian.SelectedValue = AxleCacheManager.AxleList[AxleName].Radian;

                labOnestepDisplacement.Content = getOnestepDisplacementString(AxleCacheManager.AxleList[AxleName].OnestepDisplacement);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("AxleSettings.xaml加载异常:{0}", ex.Message));
            }
        }

        static string getOnestepDisplacementString(double dValue)
        {
            string osd = dValue.ToString(MySetting.OneStepDisDeciFormatter);
            if (!string.IsNullOrEmpty(osd)
                && osd.IndexOf(".") >= 0
                && osd.EndsWith("0")
                )
            {
                osd = osd.TrimEnd('0');
            }
            return osd;
        }


        public static DependencyProperty AxleNameProperty = DependencyProperty.Register(
        "AxleName", typeof(string)
        , typeof(AxleSettings)
        , new PropertyMetadata(string.Empty)
    );

        public string AxleName
        {
            get { return (string)GetValue(AxleNameProperty); }
            set { SetValue(AxleNameProperty, value); }
        }

        private void cmbPssType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bindRunningUnits();
            bindLeadDistances();
            bindDriveRatios();
            bindAxleDetailSettings();
            bindRadians();
        }

        #region 绑定
        void bind()
        {
            bindPssType();
        }

        /// <summary>
        /// 电移台类型
        /// </summary>
        private static List<PssType> s_pssTypeList = new List<PssType>()
                {
                new PssType((int)PowerShiftStations.NoConnected,"未联接"),
                new PssType((int)PowerShiftStations.Translational,"平移台"),
                new PssType((int)PowerShiftStations.Whirling,"旋转台")
                };
        /// <summary>
        /// 运行单位
        /// </summary>
        private static List<RunningUnit> s_runningUnits = new List<RunningUnit>()
        {
                new RunningUnit((int)RunningUnits.Step,"步数"),
                new RunningUnit((int)RunningUnits.Millimeter,"毫米"),
                new RunningUnit((int)RunningUnits.Radian,"度数")
                //,new RunningUnit((int)RunningUnits.UnDefined,"未定义")
        };
        /// <summary>
        /// 细分参数设定
        /// </summary>
        private static List<int> s_DetailSettings = new List<int>() { 1, 2, 4, 8, 16, 32, 64, 128 };
        /// <summary>
        /// 电移台电机度数
        /// </summary>
        private static List<double> s_Radians = new List<double> { 0.9, 1.8 };

        /// <summary>
        /// 丝杆导程
        /// </summary>
        private static List<double> s_LeadDistance = new List<double> { 1, 2, 4, 5, 8, 10 };

        /// <summary>
        /// 传动比
        /// </summary>
        private static List<double> s_DriveRatio = new List<double> { 90, 180, 270, 360, 400, 720 };

        /// <summary>
        /// 电移台类型
        /// </summary>
        void bindPssType()
        {
            cmbPssType.ItemsSource = s_pssTypeList;
            cmbPssType.DisplayMemberPath = "Name";
            cmbPssType.SelectedValuePath = "ID";
            cmbPssType.SelectedIndex = 0;
        }

        #region 运行单位
        public int RunningUnit
        {
            get
            {
                return cmbRunUnit.SelectedValue == null
                      ? (int)RunningUnits.UnDefined
                      : (int)cmbRunUnit.SelectedValue;
            }
        }
        void bindRunningUnits()
        {
            List<RunningUnit> mList = new List<RunningUnit>(s_runningUnits);
            PowerShiftStations pssType = (PowerShiftStations)cmbPssType.SelectedValue;
            cmbRunUnit.IsEnabled = true;
            switch (pssType)
            {
                case PowerShiftStations.NoConnected:
                    mList.Clear();
                    cmbRunUnit.IsEnabled = false;
                    break;
                case PowerShiftStations.Translational:
                    mList.RemoveAt((int)RunningUnits.Radian);
                    break;
                case PowerShiftStations.Whirling:
                    mList.RemoveAt((int)RunningUnits.Millimeter);
                    break;
                default:
                    mList.Clear();
                    cmbRunUnit.IsEnabled = false;
                    break;
            }
            if (mList != null && mList.Count > 0)
            {
                cmbRunUnit.ItemsSource = mList;
                cmbRunUnit.DisplayMemberPath = "Name";
                cmbRunUnit.SelectedValuePath = "ID";
                if (AxleCacheManager.AxleList[AxleName] != null)
                {
                    cmbRunUnit.SelectedIndex = (int)AxleCacheManager.AxleList[AxleName].RunningUnit;
                }
                else
                {
                    cmbRunUnit.SelectedIndex = 0;
                }
            }
        }
        #endregion

        #region 丝杆导程(平移台)
        void bindLeadDistances()
        {
            List<double> mList = new List<double>(s_LeadDistance);
            //for(int i=0;i<101;i++)
            //{
            //    mList.Add(i);
            //}
            PowerShiftStations pssType = (PowerShiftStations)cmbPssType.SelectedValue;

            cmbLeadDistance.IsEnabled = false;
            switch (pssType)
            {
                //case PowerShiftStations.NoConnected:
                //    break;
                case PowerShiftStations.Translational:
                    spLeadDistance.IsEnabled = true;
                    cmbLeadDistance.IsEnabled = true;

                    break;
                //case PowerShiftStations.Whirling:
                //    break;
                default:
                    mList.Clear();
                    spLeadDistance.IsEnabled = false;
                    cmbLeadDistance.IsEnabled = false;

                    break;
            }
            if (mList != null && mList.Count > 0)
            {
                cmbLeadDistance.ItemsSource = mList;
                //cmbLeadDistance.SelectedIndex = 0;
                try
                {
                    if (AxleCacheManager.AxleList.ContainsKey(m_axleName) && AxleCacheManager.AxleList[m_axleName] != null)
                    {
                        cmbLeadDistance.BindValue(AxleCacheManager.AxleList[m_axleName].LeadDistance);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        #endregion

        #region 传动比(旋转台)
        void bindDriveRatios()
        {
            List<double> mList = new List<double>(s_DriveRatio);
            //for (int i = 0; i <= 72; i++)
            //{
            //    mList.Add(i*5);
            //}
            PowerShiftStations pssType = (PowerShiftStations)cmbPssType.SelectedValue;

            cmbDriveRatio.IsEnabled = false;
            switch (pssType)
            {
                //case PowerShiftStations.NoConnected:
                //    break;
                //case PowerShiftStations.Translational:
                //    break;
                case PowerShiftStations.Whirling:
                    spDriveRatio.IsEnabled = true;
                    cmbDriveRatio.IsEnabled = true;
                    break;
                default:
                    mList.Clear();
                    spDriveRatio.IsEnabled = false;
                    cmbDriveRatio.IsEnabled = false;
                    break;
            }
            if (mList != null && mList.Count > 0)
            {
                cmbDriveRatio.ItemsSource = mList;
                //cmbDriveRatio.SelectedIndex = 0;
                try
                {
                    if (AxleCacheManager.AxleList.ContainsKey(m_axleName) && AxleCacheManager.AxleList[m_axleName] != null)
                    {
                        cmbDriveRatio.BindValue(AxleCacheManager.AxleList[m_axleName].DriveRatio);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        #endregion

        #region 细分参数设定
        void bindAxleDetailSettings()
        {
            List<int> mList = new List<int>(s_DetailSettings);
            PowerShiftStations pssType = (PowerShiftStations)cmbPssType.SelectedValue;

            cmbAxleDetailSetting.IsEnabled = true;
            switch (pssType)
            {
                case PowerShiftStations.NoConnected:
                    cmbAxleDetailSetting.IsEnabled = false;
                    break;
                //case PowerShiftStations.Translational:
                //    break;
                //case PowerShiftStations.Whirling:
                //    break;
                default:
                    //mList.Clear();
                    cmbAxleDetailSetting.IsEnabled = true;
                    break;
            }
            if (mList != null && mList.Count > 0)
            {
                cmbAxleDetailSetting.ItemsSource = mList;
                //cmbAxleDetailSetting.SelectedIndex = 0;
                try
                {
                    if (AxleCacheManager.AxleList.ContainsKey(m_axleName) && AxleCacheManager.AxleList[m_axleName] != null)
                    {
                        cmbAxleDetailSetting.SelectedValue = AxleCacheManager.AxleList[m_axleName].AxleDetailSetting;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        #endregion

        #region 电移台电机度数
        void bindRadians()
        {
            List<double> mList = new List<double>(s_Radians);
            PowerShiftStations pssType = (PowerShiftStations)cmbPssType.SelectedValue;

            cmbRadian.IsEnabled = true;
            switch (pssType)
            {
                case PowerShiftStations.NoConnected:
                    cmbRadian.IsEnabled = false;
                    break;
                //case PowerShiftStations.Translational:
                //    break;
                //case PowerShiftStations.Whirling:
                //    break;
                default:
                    //mList.Clear();
                    cmbRadian.IsEnabled = true;
                    break;
            }
            if (mList != null && mList.Count > 0)
            {
                cmbRadian.ItemsSource = mList;
                //cmbRadian.SelectedIndex = 0;
                try
                {
                    if (AxleCacheManager.AxleList.ContainsKey(m_axleName) && AxleCacheManager.AxleList[m_axleName] != null)
                    {
                        cmbRadian.SelectedValue = AxleCacheManager.AxleList[m_axleName].Radian;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        #endregion

        private void cmbRunUnit_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OnUnitChanged != null && cmbRunUnit.SelectedValue != null)
            {
                RunningUnit ru = cmbRunUnit.SelectedItem as RunningUnit;
                //AxleCacheManager.AxleList[AxleName] = AxleCacheManager.getAxle(AxleName);
                AxleCacheManager.AxleList[AxleName].RunningUnit = (RunningUnits)ru.ID;
                AxleCacheManager.Update(AxleCacheManager.AxleList[AxleName]);
                if (ru != null && !string.IsNullOrEmpty(ru.Name))
                {
                    OnUnitChanged(AxleName, ru.ID);
                }

            }
        }

        private void cmbAxleDetailSetting_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbAxleDetailSetting.SelectedValue != null)
            {
                int sValue = 0;
                if(int.TryParse(cmbAxleDetailSetting.SelectedValue.ToString(),out sValue))
                {
                    if (AxleCacheManager.AxleList.ContainsKey(m_axleName))
                    {
                        if (AxleCacheManager.AxleList[m_axleName].AxleStatus != AxleStatus.Stoped)
                        {
                            setState(string.Format("[{0}] 轴正在运行，请稍候再试!",m_axleName));
                            return;
                        }
                    }
                    AxleManager.StepperAngleFractionIM(m_axleName, sValue);
                }
            }
        }

        #region 单步运行位移
        #endregion

        #endregion

        void setState(string state)
        {
            Data.AxleStateBarMsg.Instance.AxleState = state;
        }
    }
}
